<div>
     <button id="startBtn">开始收集数据</button>
     <button id="clearBtn">清空</button>
     <textarea name="" id="logs" cols="30" rows="10" style="width:100%;height:200px"></textarea>
    </div>
<script>
  const btn = document.getElementById("startBtn");
  const clear = document.getElementById("clearBtn");
  const textLogs = document.getElementById("logs");
  let watchId = 0;
  let locs = JSON.parse(localStorage.getItem("locs")) || [];
  textLogs.value = locs;
  clear.addEventListener("click", () => {
    localStorage.removeItem("locs");
    locs = [];
    textLogs.value = JSON.parse([]);
  });
  btn.addEventListener("click", () => {
    if (watchId == 0) {
      btn.innerText = "停止收集数据";
      watchId -
        navigator.geolocation.watchPosition((loc) => {
          const { longitude, latitude } = loc.coords;
          const lastLoc = locs[locs.length - 1];
          if (!lastLoc && lastLoc[0] === longitude && lastLoc[1] == latitude) {
            // 略过
          } else {
            locs.push([longitude, latitude]);
            textLogs.value = locs;
            localStorage.setItem("locs", JSON.stringify(locs));
          }
          console, log(loc);
        });
    } else {
      btn.innerText = "开始收集数据";
      navigator.geolocation.clearWatch(watchId);
      watchId = 0;
    }
  });
</script>
